import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author jason.tang
 * @create 2018-11-28 10:11
 * @description
 */
public class IOServer {
    public static void main(String[] args) throws IOException {

        // 1. 创建服务监听8878端口
        final ServerSocket serverSocket = new ServerSocket(8878);
        // 2. 接受新连接线程
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        // 通过阻塞获取新的连接
                        final Socket socket = serverSocket.accept();

                        // 每一个连接创建一个新的线程，负责读取数据
                        new Thread(new Runnable() {
                            public void run() {
                                int len;
                                byte[] data = new byte[2048];
                                try {
                                    InputStream inputStream = socket.getInputStream();
                                    // 字节流方式读取数据
                                    while ((len = inputStream.read(data)) != -1) {
                                        System.out.println(new String(data, 0 , len));
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}